// 云函数入口文件
const cloud = require('wx-server-sdk')
const request = require('request');
const WXBizDataCrypt = require('./WXBizDataCrypt')
cloud.init()
// 云函数入口函数
let appid = 'wx1506ab5e09bac4f7';
let secret = 'bbf0f4223c9f3f4a06b15d5536df2b47';
let requestApi=function(c){
    return new Promise((resolve,reject)=>{
      let opts = {
        url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${c}&grant_type=authorization_code`
      }
      request(opts, (err, data) => {
        if (err) reject(err);
        resolve(data);
      })
    })
}

exports.main = async(event, context) => {
  let code=event.code;
  let enData=event.enData;
  let iv=event.iv;
  console.log(event);
  let al= await requestApi(code);
  let sessionKey=JSON.parse(al.body);
  let session_key = sessionKey.session_key;
  console.log(session_key)
  let pc = new WXBizDataCrypt(appid, session_key)
  return pc.decryptData(enData, iv)
}